﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WJ.DataSender.Service.Commen;
using WJ.DataSender.Service.Models;
using WJ.DataSender.Service.Models.ConfigModel;

namespace WJ.DataSender.Service.Implement
{
    public class BaseMessageHandle<T, U> : IMessageHandle<T, U> where T : IModel where U : IResultModel
    {


        private HttpMethod DefaultMethod = HttpMethod.Get;

        private readonly IHttpClientFactory _httpClientFactory;

        public string PlatformUrl { get; set; }
        public string PlatformName { get; set; }
        public bool StopSend { get; set ; }

        public BaseMessageHandle(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 内部处理HttpRequest对象
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual HttpRequestMessage HandleRequest(HttpMethod method, string url, T message)
        {
            var request = new HttpRequestMessage(method, url);
            request.Headers.Add("Accept", "application/vnd.github.v3+json");
            request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
            if (message != null)
            {
                request.Content = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8);
            }
            return request;
        }


        /// <summary>
        /// 指定平台发送消息
        /// </summary>
        /// <param name="method"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual async Task<U> SendMessageAsync(HttpMethod method, T message)
        {
            if (string.IsNullOrWhiteSpace(PlatformUrl))
            {
                throw new ArgumentNullException(nameof(PlatformUrl));
            }
            if (_httpClientFactory is null)
            {
                throw new ArgumentNullException(nameof(_httpClientFactory));
            }
            try
            {
                var request = HandleRequest(method, PlatformUrl, message);
                var httpClient = _httpClientFactory.CreateClient();
                httpClient.Timeout = new TimeSpan(0, 0, CacheValues.AppsettingConfig.TimeOut);
                var response = await httpClient.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<U>(response.Content.ReadAsStringAsync().Result);
                    return result;
                }
                else
                {
                    throw new HttpRequestException($"{PlatformName}平台接口:{PlatformUrl}无法访问,响应码：【{response.StatusCode}】，返回消息：【{response.Content.ReadAsStringAsync().Result}】，请求消息：【{request.RequestUri}-{request.Content.ReadAsStringAsync().Result}】");
                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public virtual async Task<U> PostAsync(string jsonStr)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient();
                httpClient.Timeout = new TimeSpan(0, 0, CacheValues.AppsettingConfig.TimeOut);
                var response = await httpClient.PostAsync(PlatformUrl, new StringContent(jsonStr, Encoding.UTF8)); ;
                if (response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<U>(response.Content.ReadAsStringAsync().Result);
                    return result;
                }
                else
                {
                    throw new HttpRequestException($"{PlatformName}平台接口:{PlatformUrl}无法访问,响应码：【{response.StatusCode}】,请求内容：【{jsonStr}】");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public virtual async Task<U> GetAsync()
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient();
                httpClient.Timeout = new TimeSpan(0, 0, CacheValues.AppsettingConfig.TimeOut);
                AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"root:root")));
                httpClient.DefaultRequestHeaders.Authorization = authentication;
                var response = await httpClient.GetAsync(PlatformUrl); 
                if (response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<U>(response.Content.ReadAsStringAsync().Result);
                    return result;
                }
                else
                {
                    throw new HttpRequestException($"{PlatformName}平台接口:{PlatformUrl}无法访问,响应码：【{response.StatusCode}】");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public object ReciveMessage()
        {
            throw new NotImplementedException();
        }
    }
}
